# =============================================================================
# Exercises in validity - R code
# Advanced course in questionnaire technique and clinimetrics
#
# Reproduces Tables 1-5 and the graphs used in the exercise text.
# The results are identical to the Stata log files (Appendix 1-3).
#
# Data files (place them in the same folder as this script):
#   criterion validity sf12.dta   (Exercise 1.1)
#   criterion validity cancer.dta (Exercise 1.2)
#   construct validity.dta        (Exercise 1.3)
#
# The package 'haven' is needed to read Stata files:
#   install.packages("haven")
# Everything else uses base R.
# =============================================================================

library(haven)

# Change to the folder containing the data files (insert your own path)
setwd("C:/your/folder")

# Helper: n, mean, SD and 95% CI for a mean (missing values removed)
describe <- function(x) {
  x  <- x[!is.na(x)]
  n  <- length(x)
  m  <- mean(x)
  s  <- sd(x)
  ci <- m + c(-1, 1) * qt(0.975, n - 1) * s / sqrt(n)
  c(n = n, mean = m, sd = s, ci_lower = ci[1], ci_upper = ci[2])
}


# =============================================================================
# Exercise 1.1 - criterion validity, continuous instrument and gold standard
# Variables: pcs_sf12 (PCS from SF-12), pcs_sf36 (PCS from SF-36), baseline
# =============================================================================

d1 <- zap_labels(read_dta("criterion validity sf12.dta"))
d1 <- d1[complete.cases(d1$pcs_sf12, d1$pcs_sf36), ]   # 123 complete pairs

# differences and averages
d1$diff <- d1$pcs_sf12 - d1$pcs_sf36
d1$ave  <- (d1$pcs_sf12 + d1$pcs_sf36) / 2

# Table 1: n, mean, SD and 95% CI for SF-12, SF-36 and the difference
round(rbind("SF-12 PCS"  = describe(d1$pcs_sf12),
            "SF-36 PCS"  = describe(d1$pcs_sf36),
            "Difference" = describe(d1$diff)), 2)

# Table 1: paired t-test of mean difference = 0
t.test(d1$pcs_sf12, d1$pcs_sf36, paired = TRUE)

# Limits of agreement: mean difference +/- 1.96*SD
n   <- nrow(d1)
m   <- mean(d1$diff)
s   <- sd(d1$diff)
z   <- qnorm(0.975)
loa <- m + c(-1, 1) * z * s

# 95% CI's for the limits of agreement
# (same formula as Stata's -centile ..., meansd-)
se_loa <- s * sqrt(1 / n + z^2 / (2 * (n - 1)))
round(rbind(lower_LoA = c(LoA = loa[1], ci_lower = loa[1] - z * se_loa, ci_upper = loa[1] + z * se_loa),
            upper_LoA = c(LoA = loa[2], ci_lower = loa[2] - z * se_loa, ci_upper = loa[2] + z * se_loa)), 2)

# Graph "Scatter plot.png": differences against averages
plot(d1$ave, d1$diff, pch = 19,
     xlab = "(PCS_SF12 + PCS_SF36)/2", ylab = "PCS_SF12 - PCS_SF36")

# Bland-Altman plot: lines at 0, the mean difference and the limits of agreement
plot(d1$ave, d1$diff, pch = 19, main = "Bland-Altman plot",
     xlab = "(PCS_SF12 + PCS_SF36)/2", ylab = "PCS_SF12 - PCS_SF36",
     ylim = range(c(d1$diff, loa)))
abline(h = 0, lty = 2)
abline(h = m)
abline(h = loa, col = "blue")

# Graph "qq_diff_1_1.png": QQ-plot of the differences
qqnorm(d1$diff, pch = 19, main = "QQ-plot of the differences")
qqline(d1$diff)


# =============================================================================
# Exercise 1.2 - criterion validity, dichotomous instrument and gold standard
# Variables: test (new instrument, 1 = positive), criterion (gold standard,
#            1 = cancer)
# =============================================================================

d2 <- zap_labels(read_dta("criterion validity cancer.dta"))

# Table 2: test result (rows) against gold standard (columns)
tab2 <- table(Test = factor(d2$test,      levels = c(1, 0), labels = c("+", "-")),
              Gold = factor(d2$criterion, levels = c(1, 0), labels = c("+", "-")))
addmargins(tab2)

TP <- tab2["+", "+"]; FP <- tab2["+", "-"]
FN <- tab2["-", "+"]; TN <- tab2["-", "-"]

# Sensitivity, specificity, PPV and NPV "by hand"
c(Sensitivity = TP / (TP + FN),
  Specificity = TN / (TN + FP),
  PPV         = TP / (TP + FP),
  NPV         = TN / (TN + FN))

# Prevalence, and the PPV and NPV expected if sensitivity = 0.85 and
# specificity = 0.95 (the researchers' hypotheses)
p <- (TP + FN) / sum(tab2)
c(Prevalence   = p,
  Expected_PPV = 0.85 * p / (0.85 * p + (1 - 0.95) * (1 - p)),
  Expected_NPV = 0.95 * (1 - p) / (0.95 * (1 - p) + (1 - 0.85) * p))

# Table 3: estimates with exact binomial 95% CI's (as -diagt- in Stata)
exact_ci <- function(x, n) {
  ci <- binom.test(x, n)$conf.int
  100 * c(estimate = x / n, ci_lower = ci[1], ci_upper = ci[2])
}
round(rbind(Sensitivity = exact_ci(TP, TP + FN),
            Specificity = exact_ci(TN, TN + FP),
            PPV         = exact_ci(TP, TP + FP),
            NPV         = exact_ci(TN, TN + FN)), 1)


# =============================================================================
# Exercise 1.3 - construct validity
# Variables: whiscore7_1 (WI-7), scl8score_1 (SCL-8), pcs_1 and mcs_1 (SF-36
#            PCS and MCS), psychiatric_comorbidity (0 = no, 1 = yes),
#            gender (0 = female, 1 = male); all at baseline
# =============================================================================

d3 <- as.data.frame(zap_labels(read_dta("construct validity.dta")))
vars <- c("whiscore7_1", "scl8score_1", "pcs_1", "mcs_1")

# Graph "qq_1_3.png": QQ-plots of the four scores
op <- par(mfrow = c(2, 2))
for (v in vars) {
  qqnorm(d3[[v]], pch = 19, main = v)
  qqline(d3[[v]])
}
par(op)

# Graph "scatter_1_3.png": scatterplot matrix
pairs(d3[, vars], lower.panel = NULL, pch = 19)

# Table 4: Pearson and Spearman correlations with 95% CI's
# The CI's use Fisher's z-transformation (as -corrci- in Stata). Spearman's
# correlation and CI are computed as Pearson's correlation on the ranked
# variables, exactly as in the Stata code.
corr_ci <- function(x, y) {
  ok <- complete.cases(x, y)
  r  <- cor.test(x[ok], y[ok])
  c(n = sum(ok), r = unname(r$estimate), ci_lower = r$conf.int[1], ci_upper = r$conf.int[2])
}
rk <- function(x) rank(x, na.last = "keep")   # average ranks for ties

others <- c("SCL-8" = "scl8score_1", "SF-36 MCS" = "mcs_1", "SF-36 PCS" = "pcs_1")
round(t(sapply(others, function(v) corr_ci(d3$whiscore7_1, d3[[v]]))), 2)          # Pearson
round(t(sapply(others, function(v) corr_ci(rk(d3$whiscore7_1), rk(d3[[v]])))), 2)  # Spearman

# Graphs "qq_1_3_no_comor.png", "qq_1_3_comor.png", "qq_1_3_female.png",
# "qq_1_3_male.png"
op <- par(mfrow = c(2, 2))
groups <- list("No comorbidity" = d3$psychiatric_comorbidity == 0,
               Comorbidity      = d3$psychiatric_comorbidity == 1,
               Female           = d3$gender == 0,
               Male             = d3$gender == 1)
for (g in names(groups)) {
  y <- d3$whiscore7_1[groups[[g]] %in% TRUE]
  qqnorm(y, pch = 19, main = g)
  qqline(y)
}
par(op)

# Table 5: n, mean, SD and 95% CI by group
round(rbind("No comorbidity" = describe(d3$whiscore7_1[d3$psychiatric_comorbidity == 0]),
            Comorbidity      = describe(d3$whiscore7_1[d3$psychiatric_comorbidity == 1]),
            Women            = describe(d3$whiscore7_1[d3$gender == 0]),
            Men              = describe(d3$whiscore7_1[d3$gender == 1])), 1)

# Table 5: differences between groups (unpaired t-test, equal SDs assumed).
# The difference is group 0 minus group 1 (no - yes; women - men).
t.test(whiscore7_1 ~ psychiatric_comorbidity, data = d3, var.equal = TRUE)   # H5
t.test(whiscore7_1 ~ gender,                  data = d3, var.equal = TRUE)   # H6

# Alternative without assuming equal standard deviations (Welch)
t.test(whiscore7_1 ~ psychiatric_comorbidity, data = d3)
t.test(whiscore7_1 ~ gender,                  data = d3)
